<template>
  <el-card header="修改密码" shadow="never">
    <el-alert show-icon style="margin-bottom: 15px;" title="密码更新成功后，您将被重定向到登录页面，您可以使用新密码重新登录。" type="info"/>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" style="margin-top:20px;">
      <el-form-item label="当前密码" prop="password">
        <el-input v-model="form.password" placeholder="请输入当前密码" show-password type="password"></el-input>
        <div class="el-form-item-msg">必须提供当前登录用户密码才能进行更改</div>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" placeholder="请输入新密码" show-password type="password"></el-input>
        <div class="el-form-item-msg">请输入包含英文、数字的8位以上密码</div>
      </el-form-item>
      <el-form-item label="确认新密码" prop="surePassword">
        <el-input v-model="form.surePassword" placeholder="请再次输入新密码" show-password
                  type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存密码</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
module.exports = {
  data() {
    return {
      form: {
        userId: this.$TOOL.data.get("APP_USER_INFO").userId,
        password: "",
        newPassword: "",
        surePassword: ""
      },
      rules: {
        password: [
          {required: true, message: '请输入当前密码'}
        ],
        newPassword: [
          {required: true, message: '请输入新密码'}
        ],
        surePassword: [
          {required: true, message: '请再次输入新密码'},
          {
            validator: (rule, value, callback) => {
              if (value !== this.form.newPassword) {
                callback(new Error('两次输入密码不一致'));
              } else {
                callback();
              }
            }
          }
        ]
      }
    }
  },
  methods: {
    save() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$API.user.updateUserPassword.put({
            userId: this.form.userId,
            password: this.$TOOL.crypto.rsaEncrypt(this.form.password),
            newPassword: this.$TOOL.crypto.rsaEncrypt(this.form.newPassword),
            surePassword: this.$TOOL.crypto.rsaEncrypt(this.form.surePassword)
          }).then(response => {
            if (response.status) {
              this.$API.auth.logout.get().then(res => {
                this.$TOOL.data.clear();
                this.$alert(response.msg, "成功", {
                  type: 'success',
                  center: true
                }).then(() => {
                  this.$router.replace({
                    path: '/login'
                  })
                }).catch(() => {
                })
              })
            } else {
              this.$alert(response.msg, "提示", {type: 'error'});
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style>
</style>
